package cn.u313.lymusic.activity

import android.Manifest
import android.content.pm.PackageManager
import android.media.MediaScannerConnection
import android.os.Environment
import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.TextFieldColors
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onKeyEvent
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProvider
import cn.u313.lymusic.R
import cn.u313.lymusic.model.SearchModel
import cn.u313.lymusic.model.SearchModel.Data
import cn.u313.lymusic.ui.dialog.DownloadFromDialog
import cn.u313.lymusic.ui.dialog.loading.LoadingDialog
import cn.u313.lymusic.utils.FilePermissionUtil
import cn.u313.lymusic.utils.Height
import cn.u313.lymusic.utils.Width
import cn.u313.lymusic.viewmodel.MusicDownloadViewModel
import coil.compose.AsyncImage
import com.arialyy.aria.core.Aria


class MainActivity : BaseActivity() {
    val musicVm by lazy {
        ViewModelProvider(this)[MusicDownloadViewModel::class.java]
    }
    val REQUEST_CODE: Int = 1

    private fun requestPermission() {
        // 检查是否已经有了权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED
        ) {
            // 申请权限
            ActivityCompat.requestPermissions(
                this,
                arrayOf<String>(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                REQUEST_CODE
            )
        }
    }

    @Composable
    override fun InitView() {
        FilePermissionUtil(this).requestReadPermission(this, 100)
        IndexHome(musicVm) {
            DownloadFromDialog(it, musicVm).show(this.supportFragmentManager, "name")
        }
    }

    val loadingDialog: LoadingDialog by lazy { LoadingDialog(this) }
    override fun initData() {
        setSystemBarTransparent()
        requestPermission()
        musicVm.playUrl.observe(this) {
            runOnUiThread {
                Toast.makeText(this, "开始下载", Toast.LENGTH_SHORT).show()
            }
            if (it != null) {
                Aria.download(this)
                    .load(it)
                    .ignoreCheckPermissions()
                    .setFilePath(
                        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                            .getPath() + String.format(
                            "/%s.%s",
                            musicVm.musicInfo.value?.fileName(),
                            if (it.contains("flac")) "flac" else "mp3"
                        )
                    )
                    .create()
            };
        }
        musicVm.isLoadding.observe(this) {
            if (it) {
                if (loadingDialog.isShowing) return@observe
                loadingDialog.show()
            } else {
                if (loadingDialog.isShowing.not()) return@observe
                loadingDialog.dismiss()
            }
        }
    }
}

//@Preview
@Composable
fun IndexHome(musicVm: MusicDownloadViewModel, clickDownload: (Data) -> Unit) {
    val value =
        musicVm.searchModel.observeAsState().value ?: SearchModel()
    Box(modifier = Modifier.fillMaxSize()) {
        Column(modifier = Modifier.fillMaxSize()) {
            Height(int = 15)
            SearchView {
                if (it.isEmpty()) {
                    return@SearchView
                }
                musicVm.showLoading()
                musicVm.search(it)
            }
            LazyColumn {
                items(value.data) {
                    SongItem(it, clickDownload)
                }
            }
        }

    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Composable
fun SearchView(clickSearch: (String) -> Unit = {}) {
    val rainbowColors = listOf(
        Color(0xFF6000FA),
        Color(0xFFD414DB),
        Color(0xFFF17A7A),
        Color(0xFF1F1C1C)
    )
    val brush = remember {
        Brush.linearGradient(
            colors = rainbowColors
        )
    }
    var text by remember { mutableStateOf("") }

    Row(
        verticalAlignment = Alignment.CenterVertically, modifier = Modifier
    ) {
        BasicTextField(
            value = text,
            onValueChange = { newText -> text = newText },
            modifier = Modifier
                .padding(10.dp)
                .fillMaxWidth()
//                .background(Color(0xffffffff), RoundedCornerShape(15))
//                .padding(10.dp)
                .weight(1f)
                .onKeyEvent { keyEvent ->
                    if (keyEvent.key == Key.Enter) {
                        // 处理回车事件
                        println("回车键被按下: ${text}")
                        false // 表示事件被消费，防止继续传递
                    } else {
                        false // 其他按键则不消费
                    }
                },
            textStyle = TextStyle(fontSize = 18.sp, brush = brush),
            decorationBox = @Composable { innerTextField ->
                // places leading icon, text field with label and placeholder, trailing icon
                TextFieldDefaults.DecorationBox(
                    value = text,
                    visualTransformation = VisualTransformation.None,
                    innerTextField = innerTextField,
                    placeholder = {
                        Text(
                            text = "输入搜索资源名称",
                            style = TextStyle(color = Color.Gray, fontSize = 18.sp)
                        )
                    },
                    shape = RoundedCornerShape(15.dp),
                    singleLine = true,
                    enabled = true,
                    isError = false,
                    colors = TextFieldDefaults.textFieldColors(
                        containerColor = Color.Transparent,
                        focusedIndicatorColor = Color.Transparent,
                        unfocusedIndicatorColor = Color.Transparent
                    ),
                    interactionSource = remember { MutableInteractionSource() },
                )
            }
        )
        Text(text = "搜索", modifier = Modifier.clickable {
            clickSearch.invoke(text)
        })
        Width(int = 16)
    }
}

//@Preview
@Composable
fun SongItem(data: SearchModel.Data, clickDownload: (Data) -> Unit) {
    Height(int = 10)
    Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
        Width(int = 20)
        RoundAsyncImage(
            modifier = Modifier
                .size(50.dp),
            data.pic
        )
        Width(int = 10)
        Column(Modifier.weight(1f)) {
            Text(text = data.song + " - " + data.singger)
            Text(text = data.album, fontSize = 12.sp)
        }
        DownloadBtn() {
            clickDownload.invoke(data)
        }
    }
}

@Composable
fun RoundAsyncImage(modifier: Modifier, url: String) {
    AsyncImage(
        model = url,
        contentDescription = null,
        modifier = modifier
            .size(100.dp)
            .clip(RoundedCornerShape(50)),
        placeholder = painterResource(id = R.drawable.ic_launcher_background), // 占位符，即加载时显示的图像，可选
        error = painterResource(id = R.drawable.ic_launcher_foreground), // 加载图片出错时显示的图像，可选
        fallback = painterResource(id = R.drawable.ic_launcher_foreground), // 加载的图像链接不存在时指定要显示的图像，可选
        onLoading = {
            // 显示进度条等
        },
        onSuccess = {
            // 隐藏进度条等
        },
        onError = { error ->
            // 隐藏进度条,错误提示等
            error.result.throwable.printStackTrace()
        },
        alignment = Alignment.Center, // 图像对其位置,默认居中显示
        contentScale = ContentScale.FillBounds, // 图像填充模式
        alpha = 1f, // 设置透明度
    )

}

@Preview
@Composable
fun DownloadBtn(clickSearch: (String) -> Unit = {}) {
    Button(
        onClick = { clickSearch.invoke("") },
        colors = ButtonDefaults.buttonColors(
            containerColor = Color(0xFF4DB3F8),
            contentColor = Color.White
        ),
        modifier = Modifier
            .padding(10.dp)
    ) {
        Text(
            text = "下载",
            style = TextStyle(fontSize = 13.sp, color = Color.White)
        )

    }
}
